<template>
  <PanelHead :route="route"></PanelHead>
  <el-button type="primary" icon="Plus" size="small" @click="handleClick(null)">新增</el-button>
  <!-- 气泡弹窗  删除按钮 -->
  <el-popconfirm title="是否确定要删除" confirm-button-text="是" cancel-button-text="否" icon="InfoFilled" icon-color="#626AEF"
    @confirm="confirmEvent">
    <template #reference>
      <el-button type="danger" size="small" icon="Delete">删除</el-button>
    </template>
  </el-popconfirm>
  <!-- 表格 -->
  <el-table :data="companionDataList.list" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="id" />
    <el-table-column prop="name" label="昵称" />
    <el-table-column prop="avatar" label="头像">
      <template #default=" scope">
        <el-image :src="scope.row.avatar"></el-image>
      </template>
    </el-table-column>
    <el-table-column label="性别">
      <template #default="scope">
        {{scope.row.sex==='1'?'男':'女'}}
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="手机号" />
    <el-table-column label="状态">
      <template #default="scope">
        <el-tag :type="scope.row.active?'success':'danger'">{{scope.row.active==='0'?'失效':'生效'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="创建时间">
      <template #default="scope">
        <div class="flex-box">
          <el-icon>
            <Clock />
          </el-icon>
          <span style="margin-left: 10px;">{{scope.row.create_time}}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="handleClick(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="pagination-info">
    <el-pagination v-model:current-page="paginationData.pageNum" :page-size="paginationData.pageSize"
      :background="false" size="small" layout="total, prev, pager, next" :total="companionDataList.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 弹窗 -->
  <el-dialog v-model="dialogTableVisible" title="陪护士添加" :before-close="beforeClose" width="500">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" label-position="left">
      <el-form-item v-show="false" prop="id">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="form.name" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-button v-if="!form.avatar" type="primary" @click="openImgDialog(null)">点击上传</el-button>
        <el-image v-else :src="form.avatar" style="width:100px;height: 100px;" @click="openImgDialog(form)"></el-image>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <div class="number-controller">
          <el-input-number v-model="form.age" :min="18" :max="50" />
        </div>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" prop="mobile"></el-input>
      </el-form-item>
      <el-form-item label="是否生效" prop="active">
        <el-radio-group v-model="form.active">
          <el-radio :value="0">失效</el-radio>
          <el-radio :value="1">生效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- 添加一个按钮插槽 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm(formRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择头像的弹窗 -->
  <el-dialog title="选择图片" width="680" v-model="dialogImgVisible" :before-close="imageBeforeClose">
    <div class="image-list">
      <div v-for="(item,index) in fileList" :key="item.name" class="img-box" @click="selectImage(item)">
        <div class="select" v-if="selectIndex === index">
          <el-icon color="#fff">
            <Check />
          </el-icon>
        </div>
        <el-image :src="item.url" style="width: 148px;height:148px" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="dialogImgVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmImage">确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
  import PanelHead from '../../../components/panelHead.vue'
  import { photoList, companionList, companionAdd, deleteCompanion } from '../../../api/login.js'
  import { useRoute } from 'vue-router'
  import { onMounted, reactive, ref, nextTick } from 'vue'
  const route = useRoute()
  const formRef = ref()
  const selectIndex = ref()
  const form = reactive({
    id: '',
    name: '',
    avatar: '',
    sex: '',
    age: 18,
    mobile: '',
    active: 1
  })

  const dialogTableVisible = ref(false)  //控制弹窗的显示和隐藏
  const dialogImgVisible = ref(false)  //控制图片选择的弹框
  const paginationData = reactive({
    pageNum: 1,
    pageSize: 10
  })
  const fileList = ref([])//存储陪护士的头像
  const selectTableData = ref([]) //存储选择要删除的数据
  const companionDataList = reactive({//存储陪护士的信息
    list: [],
    total: 0
  })
  // 校验规则
  const rules = reactive({
    name: [{ required: true, trigger: 'blur', message: '请输入昵称' }],
    avatar: [{ required: true, message: '请选择头像' }],
    sex: [{ required: true, trigger: 'change', message: '请选择性别' }],
    mobile: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
  })
  // 选择头像
  const selectImage = (item) => {
    form.avatar = item.url; // 更新头像
    selectIndex.value = fileList.value.indexOf(item); // 设置选中索引
  };
  // 打开选择头像的弹框   
  const openImgDialog = (rowData) => {
    dialogImgVisible.value = true;
    // console.log(rowData);
    // 如果是编辑状态下更换图片
    if (rowData) {
      // 查找当前头像在 fileList 中的索引并设置
      const currentIndex = fileList.value.findIndex(item => item.url === rowData.avatar);
      if (currentIndex !== -1) {
        selectIndex.value = currentIndex;
      }
    } else {
      selectIndex.value = null; // 如果是添加状态下打开弹窗时重置选中状态
    }

  };

  // 点击页码所对应的函数
  const handleSizeChange = (val) => {
    paginationData.pageSize = val
    getListData()
  }

  // 多选框选择
  const handleSelectionChange = (val) => {
    selectTableData.value = val
    // console.log(val);

  }
  // 确认删除按钮
  const confirmEvent = () => {
    // 至少要选择一个数据删除
    if (!selectTableData.value.length) {
      ElMessage.error('请选择至少一项数据')
    }
    deleteCompanion({ id: selectTableData.value }).then(({ data }) => {
      if (data.code === 10000) {
        companionListData()
      }
    })
  }

  // 点击当前页所对应的函数
  const handleCurrentChange = (val) => {
    paginationData.pageNum = val
    companionListData()
  }
  onMounted(() => {
    // 获取陪护士的头像
    photoList().then(({ data }) => {
      // console.log(data);
      fileList.value = data.data
    })
    companionListData()
  })

  // 获取陪护士的列表
  const companionListData = () => {
    companionList(paginationData).then(({ data }) => {
      const { list, total } = data.data
      companionDataList.list = list
      companionDataList.total = total
      // console.log(companionDataList);

    })
  }
  // 新增按钮 编辑按钮 打开弹框
  const handleClick = (rowData = {}) => {
    dialogTableVisible.value = true
    // 如果是编辑状态   弹窗打开后，form是异步生成的，需要填充到弹窗中
    nextTick(() => {
      if (rowData) {
        // console.log(rowData);
        Object.assign(form, rowData)
      }
    })
  }



  // 关闭前的回调，会暂停 Dialog 的关闭.
  const beforeClose = () => {
    dialogTableVisible.value = false
    formRef.value.resetFields()  //清空表单数据
  }
  const imageBeforeClose = () => {
    dialogImgVisible.value = false
  }

  // 表单提交  表单校验
  const confirm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        // 添加陪护士数据
        companionAdd(form).then(({ data }) => {
          // console.log(data);
          if (data.code === 10000) {
            ElMessage.success('添加成功')
            beforeClose()
            // 刷新列表
            companionListData()
          } else {
            ElMessage.error(data.message)
          }
        })

      } else {
        console.log('error submit!', fields)

      }
    })
  }
  // 选择完图片，点击确认按钮
  const confirmImage = () => {
    form.avatar = fileList.value[selectIndex.value].url
    dialogImgVisible.value = false
  }
</script>

<style lang="less" scoped>
  .image-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .img-box {
      position: relative;

      .select {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 24px;
        height: 24px;
        background-color: #67c23a;
        z-index: 999;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .el-image {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
</style>